package pers.byxiaobai.levelhealth.group;

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;

import pers.byxiaobai.levelhealth.config.ConfigManager;

/** 
* @author byxiaobai
* 类说明 
*/
public class GroupManager {
	public static final GroupManager INSTANCE=new GroupManager();
	
	private YamlConfiguration config;
	
	private HashMap<String,Group> groupMap;
	
	public void init() {
		config=ConfigManager.INSTANCE.getConfigYaml("config.yml");
		groupMap=new HashMap<>();
		Set<String> keys=ConfigManager.INSTANCE.getKeysByKey(config, "Group");
		  for(String key:keys) {
			  String[] sps=key.split("\\.");
			  if(sps.length==3) {
				  String groupName=sps[1];
				  Group group=getGroup(groupName);
				  if(sps[2].equalsIgnoreCase("permission")) {
					  group.setPermission(config.getString(key));
				  }
				  if(sps[2].equalsIgnoreCase("maxHealth")) {
					  group.setMaxHealth(config.getDouble(key));
				  }
			  }
		  }
	}
	
	public Group getGroup(String groupName) {
		Group group=groupMap.get(groupName);
		if(group==null) {
			group=new Group(groupName);
			groupMap.put(groupName, group);
		}
		return group;
	}
	
	public Group getGroup(Player player) {
		if(player==null||player.isOp())return null;
		Collection<Group> groups=groupMap.values();
		for(Group group:groups) {
			boolean has=player.hasPermission(group.getPermission());
			if(has) {
				return group;
			}
		}
		return null;
	}

	public YamlConfiguration getConfig() {
		return config;
	}

	public void setConfig(YamlConfiguration config) {
		this.config = config;
	}

	public HashMap<String,Group> getGroups() {
		return groupMap;
	}

	public void setGroups(HashMap<String,Group> groups) {
		this.groupMap = groups;
	}
}
